<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Event;

class UserPacket extends Base
{

    protected $name = 'user_packet';
    protected $type = [
        'free_time' => 'timestamp',
        'pay_time' => 'timestamp',
    ];
    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile,is_active,level_id,team_id');
    }
    /**
     * 创建抢红包
     */

    public function getSytoalAttr($value, $data)
    {
        $value = round(($data['price'] + $data['yield'] * $data['price'] * $data['gold']), 0) . '金币+' . round(($data['yield'] * $data['price'] * $data['integral']), 0) . '积分';
        return $value;
    }
    public function getSyAttr($value, $data)
    {
        return ($data['yield'] * 100);
    }
    /**
     * 创建抢红包
     */
    public static function createOrder($param, $user)
    {
        parent::startTrans();
        try {
            $info = Packet::where('id', $param['id'])->find();
            if ($user->level_id != 2) {
                return ['code' => -1, 'msg' => '非创客不可购买！'];
            }
            if (empty($info)) {
                return ['code' => -1, 'msg' => '抢红包不存在！'];
            }
            if ($info->end_stock <= 0) {
                return ['code' => -1, 'msg' => '剩余库存不足！'];
            }
            $find = parent::where(['uid' => $user->id, 'packet_id' => $info->id, 'status' => 1, 'pay_status' => 1])->find();
            if (!empty($find)) {
                return ['code' => -1, 'msg' => '已购买抢红包！'];
            }
            $new = parent::create([
                'sn'              => 'P' . date('YmdHis') . $user->id . rand(100000, 999999),
                'uid'             => $user->id,
                'title'      => $info->title,
                'price'      => $info->price,
                'day'      => $info->day,
                'yield'      => $info->yield,
                'integral'      => $info->integral,
                'gold'      => $info->gold,
                'packet_id'      => $info->id
            ]);
            parent::commit();
            return ['code' => 1, 'msg' => '创建成功', 'url' => url('packet/payment')->build() . '?id=' . $new->id];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取支付信息
     */
    public static function getPayment($id)
    {
        try {
            $info = parent::where('id', $id)->field('id,sn,price,pay_status')->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '无效抢红包'];
            }
            if ($info->getData('pay_status') != 0) {
                return ['code' => -1, 'msg' => '抢红包已支付或已失效'];
            }
            $data['order'] = $info;
            $data['method'] = self::payWay();

            return ['code' => 1, 'msg' => '获取成功', 'data' => $data];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    public static function payWay(): array
    {
        $method = OrderTemporary::getPaymentMethod('bonus');

        return $method;
    }
    /**
     * 支付
     */
    public static function payment($param, $user): array
    {
        try {
            $info = parent::where('id', $param['id'])->find();
            if ($info->getData('pay_status') == 1) {
                return ['code' => -1, 'msg' => '订单已支付或已失效'];
            }
            $account = $param['pay_way'];
            switch ($account) {
                case "bonus":
                    if (md5($param['pay_password']) != $user->pay_password) {
                        return ['code' => -1, 'msg' => '支付密码错误'];
                    }
                    if ($user->assets->$account < $info->price) {
                        return ['code' => -1, 'msg' => '金币不足'];
                    }
                    return self::operations($info, $user, $account);
                default:
                    return ['code' => -1, 'msg' => '支付方式错误！'];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 回调
     */
    public static function operations($info, $user, $account): array
    {

        parent::startTrans();
        try {
            $info->pay_way = $account;
            $info->pay_status = 1;
            $info->pay_time = time();
            $info->end_time = time() + $info->day * 86400;
            $info->save();
            if (!in_array($account, ['wechat', 'alipay'])) {
                Target::Account()->basics($user->id, $account, $info->price, '购买抢红包', '-')
                    ->createNormal();
            }
            parent::destroy(['pay_status' => 0, 'uid' => $user->id], true);
            Packet::where('id', $info->packet_id)->dec('end_stock', 1)->update();
            parent::commit();
            return ['code' => 1, 'msg' => '支付成功', 'url' => url('user/index')->build()];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 抢红包释放
     */
    public static function release()
    {
        parent::startTrans();
        try {
            $count = parent::where(['status' => 1, 'pay_status' => 1])->where('end_time', '<', time())->with('user')->count();
            parent::where(['status' => 1, 'pay_status' => 1])->where('end_time', '<', time())->with('user')->select()->each(function ($item) {
                $toal = round(($item->price * (1 + $item->gold * $item->yield)), 2);
                $item->status = 2;
                $item->free_time = time();
                $item->save();
                Target::Account()->basics($item->uid, 'currency', round(($item->price * $item->integral * $item->yield), 2), '抢红包释放积分收益', '+')
                    ->createNormal();
                Target::Account()->basics($item->uid, 'bonus', $toal, '抢红包释放金币收益', '+')
                    ->createBonus(0, 5);
                /**
                 * 抢红包奖励
                 */
                Relation::packetMoney($item->price, $item->user);
            });
            parent::commit();
            if($count>0){
                return ['code' => 1, 'msg' => '释放成功！'];
            }else{
                return ['code' => -1, 'msg' => '无记录释放！'];
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
